package leetcode100

// TODO 动态规划 | 状态转移方程 [经典] 【-】 最小路径和
// TODO https://leetcode.cn/problems/minimum-path-sum/solution/si-lu-qing-xi-dai-ma-jian-dan-by-damon-s-38ug/

func minPathSum(grid [][]int) int {
	m, n := len(grid), len(grid[0])
	dp := make([][]int, m) //dp[i][j]，从grid[0][0]到grid[i][j]的最小路径和
	for i := 0; i < m; i++ {
		dp[i] = make([]int, n)
	}

	dp[0][0] = grid[0][0]
	for i := 1; i < n; i++ { //计算i==0时的初始值
		dp[0][i] = dp[0][i-1] + grid[0][i]
	}
	for i := 1; i < m; i++ { //计算j==0时的初始值
		dp[i][0] = dp[i-1][0] + grid[i][0]
	}
	for i := 1; i < m; i++ {
		for j := 1; j < n; j++ {
			dp[i][j] = min2(dp[i-1][j], dp[i][j-1]) + grid[i][j]
		}
	}
	return dp[m-1][n-1]
}

func min2(a, b int) int {
	if a < b {
		return a
	}
	return b
}